/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-24 08:18:32
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-26 22:39:07
 * @FilePath: \vue3_nuxt_demo\server\api\note\index.post.ts
 * @Description: 创建文章接口
 */
import Joi from 'joi';
import { responseJson, getLoginUid, getTitle } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/**
 * 1、判断用户是否登录
 * 2、已登录则创建文章
 */

export default defineEventHandler(
  async (event) => {

    //获取用户id，判断是否登录
    const uid = getLoginUid(event);

    // 判断用户id
    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401,{
        success: false,
        msg: '请先登录'
      });
    }

    // 获取请求体
    const body = await readBody(event);

    // 数据校验
    const schema = Joi.object({
      notebookId: Joi.number().required(),
      name: Joi.string().required()
    });

    // 校验请求体
    try {
      const value = await schema.validateAsync(body);
    }
    catch (error) {
      return responseJson(400,  {
        success: false,
        msg: '参数错误',
        error: error
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {

      // 请求体
      const { notebookId, name } = body;
      //创建文章
      const [rows] = await con.execute(
        'INSERT INTO `notes` (`title`,`content_md`,`state`,`uid`) VALUE (?,?,?,?)',
        [name, '', 1, uid]
      );

      if (rows.affectedRows === 0) {
        return responseJson(400,{
          success: false,
          msg: '创建失败'
        });
      }

      //关联文集表
      const [rows2] = await con.execute(
        'INSERT INTO `notebook_notes` (`notebook_id`,`note_id`) VALUE (?,?)',
        [notebookId, rows.insertId]
      );

      if (rows2.affectedRows === 0){
        return responseJson(400,{
          success: false,
          msg: '创建失败'
        });
      }

      return responseJson(200,{
        success: true,
        msg: '创建成功'
      })

    }
    catch (error){
      // 设置响应状态码
      setResponseStatus(event,500);
      // 响应
      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }
  }
);